<template>
  <el-dialog v-model="model" @close="closedDialog">
    <el-form
      ref="resourceFormRef"
      :model="form"
      :rules="rules"
      label-width="160"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('sysMenu.module')" prop="moduleId">
            <el-select
              v-model="form.moduleId"
              clearable
              :placeholder="$t('sysMenu.moduleRequired')"
              :style="styleWidth"
            >
              <el-option
                v-for="item in moduleLists"
                :key="item.moduleId"
                :label="item.moduleName"
                :value="item.moduleId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('sysMenu.parent')" prop="parentId">
            <el-tree-select
              v-model="form.parentId"
              :data="treeData"
              filterable
              clearable
              check-strictly
              :render-after-expand="false"
              :style="styleWidth"
              :placeholder="$t('sysMenu.parentRequired')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('sysMenu.type')" prop="resourceType">
            <jmash-enum-radio
              v-model="form.resourceType"
              :data="Dict.resourceTypeEnum.values"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('sysMenu.icon')" prop="icon">
            <icon-select v-model="form.icon" @icon-value="iconValue" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('sysMenu.name')" prop="resourceName">
            <el-input
              v-model="form.resourceName"
              clearable
              :placeholder="$t('sysMenu.nameRequired')"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.resourceType !== 'other'" :span="12">
          <el-form-item :label="$t('sysMenu.target')" prop="target">
            <el-input
              v-model="form.target"
              clearable
              :placeholder="$t('sysMenu.targetRequired')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('sysMenu.resourceCode')" prop="resourceCode">
            <el-input
              v-model="form.resourceCode"
              clearable
              :placeholder="$t('sysMenu.resourceCodeRequired')"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.resourceType !== 'other'" :span="12">
          <el-form-item :label="$t('sysMenu.url')" prop="url">
            <el-input
              v-model="form.url"
              clearable
              :placeholder="$t('sysMenu.urlRequired')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col v-if="form.resourceType !== 'other'" :span="12">
          <el-form-item :label="$t('sysMenu.status')" prop="hidden">
            <el-radio-group v-model="form.hidden">
              <el-radio :value="false">{{ $t("common.show") }}</el-radio>
              <el-radio :value="true">{{ $t("common.hide") }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.resourceType == 'menu'" :span="12">
          <el-form-item :label="$t('sysMenu.keepAlive')" prop="keepAlive">
            <el-radio-group v-model="form.keepAlive">
              <el-radio :value="true">{{ $t("common.enable") }}</el-radio>
              <el-radio :value="false">{{ $t("common.disable") }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.resourceType !== 'catalog'">
        <el-col :span="24">
          <el-form-item :label="$t('sysMenu.operatePerm')" prop="operCodes">
            <el-checkbox
              v-model="checkedAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckedAll"
            >
              {{ $t("sysMenu.checkAll") }}/{{ $t("sysMenu.checkNoAll") }}
            </el-checkbox>
            <br />
            <div class="tree-border">
              <el-checkbox-group
                v-model="form.operCodes"
                @change="handleChecked"
              >
                <el-checkbox
                  v-for="item in operButton"
                  :key="item.operationId"
                  :label="item.operationCode"
                >
                  {{ item.operationName }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closedDialog">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" @click="submitForm">
          {{ $t("common.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, type PropType } from "vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { type FormInstance, type FormRules, ElMessage } from "element-plus";

import type {
  ResourceFormReq,
  ResourceParam,
  ResourceUpdateReq,
} from "@/api/system/menu/types";
import { moduleApi } from "@/api/system/module/index";
import { resourceApi } from "@/api/system/menu/index";
import { Dict } from "@/api/system";
const model = defineModel<boolean>();
let form = reactive<ResourceFormReq>({
  requestId: Math.random() * 10 + "",
  updateMask:
    "moduleId,parentId,resourceType,icon,resourceName,resourceCode,target,url,hidden,keepAlive",
  resourceType: "catalog",
  hidden: false,
});
const styleWidth = ref("width: 100%");
let moduleLists = ref([] as any);
let operButton = ref([] as any);
let operButtonCode = ref([] as any); // 所有的操作按钮code
const treeData = ref([]);
const checkedAll = ref(false);
const isIndeterminate = ref(false);
const resourceFormRef = ref<FormInstance>();
const urlExistValidate = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error(t("sysMenu.urlRequired")));
  } else {
    if ((form as ResourceUpdateReq).resourceId) {
      callback();
    } else {
      resourceApi.existMenu(value).then(({ data }) => {
        if (data === true) {
          callback(new Error(t("sysMenu.urlExist")));
        } else {
          callback();
        }
      });
    }
  }
  if (!form.parentId) {
    if (value.indexOf("/") === -1) {
      callback(new Error(t("sysMenu.urlExistSlash")));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const rules = reactive<FormRules<ResourceFormReq>>({
  moduleId: [
    { required: true, message: t("sysMenu.moduleRequired"), trigger: "change" },
  ],
  resourceName: [
    { required: true, message: t("sysMenu.nameRequired"), trigger: "blur" },
  ],
  resourceCode: [
    {
      required: true,
      message: t("sysMenu.resourceCodeRequired"),
      trigger: "blur",
    },
  ],
  url: [{ required: true, validator: urlExistValidate, trigger: "blur" }],
});

const props = defineProps({
  entityKey: {
    type: Object as PropType<ResourceParam>,
    default: () => {},
  },
});
function queryResourceData() {
  moduleApi.moduleList().then(({ data }) => {
    moduleLists.value = data.results;
  });
  resourceApi.treelist(props.entityKey?.resourceId).then(({ data }) => {
    treeData.value = data.results;
  });
  resourceApi.operList().then(({ data }) => {
    operButton.value = data.results;
    operButton.value?.forEach((i: any) =>
      operButtonCode.value.push(i.operationCode),
    );
  });
}

function iconValue(val: string) {
  form.icon = val;
}

// 全选
function handleCheckedAll(val: any) {
  form.operCodes = val ? operButtonCode.value : [];
  isIndeterminate.value = false;
}

// 单独选
function handleChecked(val: any[]) {
  form.operCodes = val;
  const checkedNum = val.length;
  checkedAll.value = checkedNum === operButtonCode.value.length;
  isIndeterminate.value =
    checkedNum > 0 && checkedNum < operButtonCode.value.length;
}
queryResourceData();

/** 展示下拉图标 */
const emits = defineEmits(["refresh", "reload"]);

const update = ref(props.entityKey && props.entityKey.resourceId !== undefined);
// 旧数据
const oldForm: ResourceFormReq = reactive({});
if (update.value) {
  resourceApi.findById(props.entityKey).then(({ data }) => {
    Object.assign(form, data);
    Object.assign(oldForm, data);
    if (form.parentId === "00000000-0000-0000-0000-000000000000") {
      form.parentId = "";
    }
  });
}

if (props.entityKey?.parentId) {
  form.parentId = props.entityKey?.parentId;
  form.moduleId = props.entityKey?.moduleId;
}

if (form.parentId === "00000000-0000-0000-0000-000000000000") {
  form.parentId = "";
}

const submitForm = async () => {
  await resourceFormRef.value?.validate((valid) => {
    if (valid) {
      if ((form as ResourceUpdateReq).resourceId) {
        resourceApi.update(form as ResourceUpdateReq).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
            emits("reload", oldForm, response.data);
          }
        });
      } else {
        resourceApi.create(form).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
            emits("reload", response.data);
          }
        });
      }
    }
  });
};

// 关闭弹框
function closedDialog() {
  if (model.value) {
    model.value = false;
  }
}
</script>
